package com.opendi.dynamic.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.opendi.dynamic.dao.opdi.SchoolChargeDao;
import com.opendi.dynamic.dao.yw.SchoolContractDao;
import com.opendi.dynamic.model.opdi.SchoolCharge;
import com.opendi.dynamic.model.yw.SchoolContract;
import com.opendi.dynamic.service.ThridOperateService;
import com.xiaoleilu.hutool.bean.BeanUtil;
import com.xiaoleilu.hutool.util.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
public class ThridOperateServiceImpl implements ThridOperateService {

    @Autowired
    private SchoolChargeDao db1ChargeDao;
    @Autowired
    private SchoolContractDao db2ContractDao;
    @Transactional
    @Override
    public void addSchoolCharge() {
        for(Integer i=0;i<10;i++)
        {
            int num = (int)(Math.random()*10);
            SchoolCharge schoolCharge = new SchoolCharge();
            schoolCharge.setChargeDate(new Date());
            schoolCharge.setNum(num);
            db1ChargeDao.insert(schoolCharge);
        }
    }

    // 同步多数据源数据
    @Transactional
    @Override
    public void syncData() {
        // 查询数据源1结果列表数据
       List<SchoolCharge> list = db1ChargeDao.selectList(Wrappers.<SchoolCharge>lambdaQuery());
       if(CollectionUtil.isNotEmpty(list)) // 查询结果不为空
       {
           // 删除数据源2数据
           db2ContractDao.delete(Wrappers.<SchoolContract>lambdaUpdate());
           List<SchoolContract> db2ContractList = new ArrayList<SchoolContract>();
           // 遍历数据源1结果数据
           list.forEach(schoolCharge -> {
               SchoolContract schoolContract =new SchoolContract();
               // 拷贝数据,从一个对象拷贝数据到另一个对象
               BeanUtil.copyProperties(schoolCharge, schoolContract);
               db2ContractList.add(schoolContract);
           });
           // 更新同步数据
           db2ContractList.forEach(db2Contract->{
               db2ContractDao.insert(db2Contract);
           });
       }
    }
}
